/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.recursos.beans;

import com.recursos.interceptors.InterceptorAuditoria;
import com.recursos.modelo.DatosUsuario;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

/**
 *
 * @author MARA
 */
@Stateless
@LocalBean
//@Interceptors({InterceptorAuditoria.class})
public class DataBaseHelper {

    @PersistenceContext(name = "recursos")
    private EntityManager em;

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public List getList(DatosUsuario datos, Class o) {

        Query q = em.createNamedQuery(o.getSimpleName() + ".findAll");
        List list = q.getResultList();
        return list;

    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public Object findById(DatosUsuario datos, Class c, String id) {
            
        Object o = em.find(c, new BigDecimal(id));
        return o;

    }

    public List findByIdList(DatosUsuario datos, Class c, String id) {

        Object o = em.find(c, new BigDecimal(id));
        ArrayList<Object> list = new ArrayList<Object>();
        if(o != null){
            list.add(o);
        }
        return list;
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void delete(DatosUsuario datos, BigDecimal id, Class clase) {
        
        try {
            Object o = em.find(clase, id);
            em.remove(o);
            
        } catch (PersistenceException e) {
           throw e;
        }
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void save(DatosUsuario datos, Object o) {

        try {
            em.merge(o);
        } catch (PersistenceException e) {
            throw e;
        }
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void create(DatosUsuario datos, Object o) {
        try {
            em.persist(o);
        } catch (Exception ex) {
            throw ex;
        }

    }

}
